import React, {useEffect, useState} from 'react';
import store from "../store";
import {changeBuyNum} from "../store/slice/cart";
function CartList(props) {
    const [cartList,setCartList] = useState(store.getState().cart.cartList);
    useEffect(()=>{
        const unSubscribe=store.subscribe(()=>{
            console.log(11111)
            setCartList(store.getState().cart.cartList);
        })
        return ()=>{
            unSubscribe();
        }
    },[])
    return (
        <div>
            {
                cartList.length===0?<h3>购物车为空！</h3>:cartList.map(item=>(
                    <div key={item.id}>
                        <p>商品名称：{item.goodsName}</p>
                        <p>商品价格：￥{item.goodsPrice.toFixed(2)}</p>
                        <p>购买的数量：
                            <button onClick={()=>{
                                store.dispatch(changeBuyNum({id:item.id,num:-1}));
                            }}>-</button>
                                {item.buyNum}
                            <button onClick={()=>{
                                store.dispatch(changeBuyNum({id:item.id,num:1}));
                            }}>+</button></p>
                        <p>小计：￥{(item.buyNum*item.goodsPrice).toFixed(2)}</p>
                        <hr/>
                    </div>
                ))
            }
        </div>
    );
}

export default CartList;